package com.qy.util;


import java.math.BigDecimal;

public class MathUtil {

    private static double EARTH_RADIUS = 6378.137 * 1000;

    public static double getSum(double start, double end, double d) {
	double sum = 0;
	double tmp = start;
	for (; tmp <= end;) {
	    sum += tmp;
	    tmp += d;
	}
	return sum;
    }

    private static double rad(double d) {
	return d * Math.PI / 180.0;
    }

    /**
     * 获取两点之间的距离
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double GetDistance(double lat1, double lng1, double lat2,
	    double lng2) {
	double radLat1 = rad(lat1);
	double radLat2 = rad(lat2);
	double a = radLat1 - radLat2;
	double b = rad(lng1) - rad(lng2);
	double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
		+ Math.cos(radLat1) * Math.cos(radLat2)
		* Math.pow(Math.sin(b / 2), 2)));
	s = s * EARTH_RADIUS;
	// s = Math.round(s * 10000) / 10000;
	return s;
    }

    /**
     * 获取两点之间的距离
     * 传入坐标点替换成
     * @param startPoint
     *            (lat1,lng1)
     * @param endPoint
     *            (lat2,lng2)
     * @return 距离米
     */
    public static double GetDistance(String startPoint, String endPoint) {
	double distance = StaticData.no_param;
	double[] starts = turnToDoubles(startPoint);
	double[] ends = turnToDoubles(endPoint);
	if (starts != null && ends != null) {
	    double lat1 = starts[0];
	    double lng1 = starts[1];
	    double lat2 = ends[0];
	    double lng2 = ends[1];
	    distance = GetDistance(lat1, lng1, lat2, lng2);
	}
	return decimals2(distance);
    }

    /**
     * 转换数据
     * 
     * @param point
     * @return
     */
    private static double[] turnToDoubles(String point) {
	double[] tmps = null;
	String[] points = point.split(StaticData.second_split);
	if (points.length == 2) {
	    tmps = new double[2];
	    tmps[0] = Double.parseDouble(points[0]);
	    tmps[1] = Double.parseDouble(points[1]);
	}
	return tmps;
    }

    /**
     * 保留两位小数
     * 
     * @param f
     * @return
     */
    public static double decimals2(double f) {
	BigDecimal b = new BigDecimal(f);
	double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
	return f1;
    }

}
